package com.darchrow.demo.rocketmqtest;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author mdl
 * @date 2020/4/27 17:27
 */
@Slf4j
@Component
public class Producer {
    private String producerGroup = "test2_group";
    private DefaultMQProducer producer;


    @PostConstruct
    public void initMQProducer() {
        producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(JmsConfig.NAME_SERVER);
        producer.setVipChannelEnabled(false);
        producer.setRetryTimesWhenSendFailed(3);

        try {
            producer.start();
            log.info("生产者 启动成功=======");
        } catch (MQClientException e) {
            e.printStackTrace();
            log.info("生产者 启动失败=======");
        }
    }

    public SendResult send(String topic, String tags, String content) {
        Message msg = new Message(topic, tags, "", content.getBytes());
        try {
            return producer.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @PreDestroy
    public void shutDownProducer() {
        if (producer != null) {
            producer.shutdown();
        }
    }

}
